开发者

Using bash and sed

Okay, so I'm not too great at this, but I have a bash script to pick a random number, then use sed to read lines off of files. It's not working and I must have done something wrong. Could anyone correct my code?

I want the code to pull the line (random number) from each of those files, then output it as a single string (with spaces between).

NUMBER=$[ ( $RANDOM % 100 )  + 1 ]
sed -n NUMBER'p' /Users/user/Desktop/Street.txt
sed -n NUMBER'p' /Users/user/Desktop/City.txt
sed -n NUMBER'p' /Users/user/Desktop/State.txt
sed -n NUMBER'p' /Users/user/Desktop/开发者_如何学JAVAZip.txt


You probably need to use $NUMBER in your sed commands, rather than just NUMBER (or ${NUMBER} if other text is directly next to it). Example:

sed -n "${NUMBER}p" /Users/user/Desktop/Street.txt


The following script will use the same randomly chosen number to grab that line from each of the 4 input files you specified and concatenate those lines into a single variable called $outstring.

#!/bin/bash

NUMBER=$(((RANDOM % 100)+1))

for file in Street City State Zip; do
   outstring+="$(sed -n "${NUMBER}p" "./${file}.txt") "
done

echo $outstring

Note: If you want (potentially) different line numbers from each of the 4 input files, then simply put the NUMBER= statement inside the for-loop.


This has the advantage of choosing from the whole of each file rather than only the first 100 lines. It will choose a different line from each file.

for f in Street City State Zip
do
    printf '%s ' "$(shuf -n 1 "/Users/user/Desktop/$f.txt")"
done
printf '\n'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜