Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed or awk: how to call line addresses from separate file?

Tags:

sed

awk

I have 'file1' with (say) 100 lines. I want to use sed or awk to print lines 23, 71 and 84 (for example) to 'file2'. Those 3 line numbers are in a separate file, 'list', with each number on a separate line.

When I use either of these commands, only line 84 gets printed:

for i in $(cat list); do sed -n "${i}p" file1 > file2; done

for i in $(cat list); do awk 'NR==x {print}' x=$i file1 > file2; done

Can a for loop be used in this way to supply line addresses to sed or awk?

like image 322
user2138595 Avatar asked Dec 04 '22 10:12

user2138595


2 Answers

This might work for you (GNU sed):

sed 's/.*/&p/' list | sed -nf - file1 >file2

Use list to build a sed script.

like image 64
potong Avatar answered Jan 09 '23 20:01

potong


You need to do > after the loop in order to capture everything. Since you are using it inside the loop, the file gets overwritten. Inside the loop you need to do >>.

Good practice is to or use > outside the loop so the file is not open for writing during every loop iteration.

However, you can do everything in awk without for loop.

awk 'NR==FNR{a[$1]++;next}FNR in a' list file1 > file2
like image 34
jaypal singh Avatar answered Jan 09 '23 19:01

jaypal singh