0

I want to replace the lines matching a pattern from multiple files from the lines in order from another file, i have up to 500 txt files, with structure: test1.txt, test2.txt, test3.txt...

11111
22222
mock
55555
77777

and so reading file one by one we like to replace in first test1.txt file mock line with first line from mock.txt file, in second test2.txt replace mock line with second line from mock.txt file, which has structure like:

mock.txt

randomText1
randomText2
randomText3
randomText4
randomText5

and so on till the last .txt file in filder

  • 2
    Welcome to U&L! What have you tried? How did it not work as expected or intended? – DopeGhoti Jan 29 at 20:32
  • im completely new to this field, i was searching for similar cases but its kinda far from what im looking for – Ilya Pribil Jan 29 at 20:37
2

With GNU sed, you can use

cat mock.txt | sed -i -e '/mock/{R/dev/stdin' -e 'd;}' test{1..3}.txt

The GNU specific R command reads and inserts a single line at a time, unlike the standard r option which would insert all of the contents.

$ head test{1..3}.txt
==> test1.txt <==
11111
22222
randomText1
55555
77777

==> test2.txt <==
11111
22222
randomText2
55555
77777

==> test3.txt <==
11111
22222
randomText3
55555
77777
R filename

Queue a line of filename to be read and inserted into the output stream at the end of the current cycle, or when the next input line is read. Note that if filename cannot be read, or if its end is reached, no line is appended, without any error indication.

As with the r command, the special value /dev/stdin is supported for the file name, which reads a line from the standard input.

Note that reading the lines directly from the file like /mock/R mock.txt doesn't work in this context, because the -i option implies the -s option, so that the first line of mock.txt is inserted into every file.

  • Thank you, that works well, but if i have lines like this sometimes "222mock 222", and i need just replace 'mock' – Ilya Pribil Jan 31 at 20:46
1

With GNU awk (i.e. gawk) you could do:

gawk -i inplace '/mock/ { getline < "mock.txt" } 1' test{1..3}.txt

Like sed, gawk offers inplace editing. The above command looks for the regex-pattern mock, and when it finds it, it replaces it with the next line from mock.txt. The 1 is a pattern that always matches, and thus causes gawk to perform its default action, which is to print the (newly) read line. Note that you won't actually see this line during inplace-editing; the print-action is necessary for the output to be recorded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.