简体   繁体   中英

Bash: how can I (1) read in a number from line “i” in a file that contains a column of numbers and (2) assign the value to a variable?

  • I have set up a sed expression that finds an old number in a file and replaces it with a new number. I have no problem with this.

  • I have many files. For each file, i , the new number needs to come from row i of a column of data in another file (let's called it "newNumbers"), like the example below.

 1.2345 10.6789 100.101112 ... 
  • I can do this by doing (inside a for loop over file (i)):
 i = 1 while read line do var[$i]="$line" find ... # My sed expression for finding and replacing a word in file (i). i=$((i+1)) done < newNumbers 

However, this is not a good solution. "newNumbers" is so long that it will take days. I know the line I need from "newNumbers." It is line i , which corresponds to file i . So I want to read in the value from "newNumbers" at line i . I cannot get the syntax right to do this though (I am not experienced with bash). I'm using GNU sed on a Mac and have checked out several questions that seem related here. Examples that have resulted in "char1: missing command" or '"iq;d": command expects \\ followed by text'-type errors are:

gsed -n -e "${i}" newNumbers
gsed 'iq;d' newNumbers
gsed "${i}q;d" newNumbers

I don't know if this is a Mac problem (GNU sed) or some syntax problem. Thank you for any help.

This is what worked but I have no idea why! I will post it, as there are probably other people who need to deal with this when working with input and output files.

Inside my for loop over file i, which starts at 0,

j=$((i+1))
newNumber_i=$(gsed "${j}q;d" newNumbers)
echo ${i%}

I needed the "echo" statement. I got it from ghostdog74's response here: How to read output of sed into a variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM