Home > Net >  Shell: replacing file text loop using sed and lines numbers
Shell: replacing file text loop using sed and lines numbers

Time:02-18

I have two files.

The first file contains, in each line, line number and text. For example:

2   AAAA
4   BBBB
5   nnnn

this text should replace the lines in the second file - according to the first column which is the line number on the second file.

So if initially the second files was:

XXXXX
XXXXX
XXXXX
XXXXX
XXXXX
XXXXX

after the change, it would be

XXXXX
AAAA
XXXXX
BBBB
nnnn
XXXXX

I thought using sed :

sed "$Ns/XXXXX/$A/" file > file-after-change

while $N is the line number (taken from the first file) and $A will be the string from the first file.

How can i read the line number first as variable N and the string itself to a different variable (A)?

CodePudding user response:

You can use sed to transform the first file into a sed script, and then pass that to a second sed instance.

sed 's%^\([0-9]*\) *\([^ ]*\)$%\1s/XXXXX/\2/' firstfile |
sed -f - secondfile

Linux sed will happily accept -f -; on some other platforms, maybe experiment with -f /dev/stdin or just save the generated script to a temporary file, and delete it when you are done.

CodePudding user response:

Alternatively, consider to use awk.

awk 'FNR==NR { seen[$1]=$2; next } seen[FNR] { print seen[FNR]; next } 1' file1.txt file2.txt

CodePudding user response:

Ugly but working (guide is the file with line numbers and substitutions, input is the actual input file):

eval "$(cat guide | sed '/^[0-9]\  */s!^\([0-9]\ \) *\(.*\)!\1s/.*/\2/!' | sed -z "s/\n/;/g;s/.*/sed '&'/")" < input

(Requires GNU sed, I belive.)

CodePudding user response:

This might work for you (GNU sed):

sed 's/\s\ /c/' file1 | sed -f - file2

Turn file1 into a sed script and apply it to file2.

The sed script changes each line in file2 referenced by a line number in file1 to the argument following that line number.

  • Related