简体   繁体   中英

How to add iterator to each line using awk, sed or grep?

How would I use grep, sed or awk to insert an iterator to each line (row), the length of the file?

Say my data looks like this, in csv format:

1,2,3,4
1,2,3,4
1,2,3,4
1,2,3,4
.
.
.
1,2,3,4

I want to make it look like this, using grep, awk or sed (or whatever else works):

[func (func (func 0)) [1 2 3 4]]
[func (func (func 1)) [1 2 3 4]]
[func (func (func 2)) [1 2 3 4]]
.
.
.
[func (func (func N)) [1 2 3 4]]

Where N is the number of rows in the file. So basically inserting the line number, of the file, into the line itself.

In pure :

while IFS=, read -r a1 a2 a3 a4; do
    echo "[func (func (func $((c++)))) [$a1 $a2 $a3 $a4]]"
done < file

You can use awk and the NR variable.

Something like this:

awk '{ gsub(/,/, " "); print "[func (func (func "(NR-1)")) ["$0"]]"; }' datafile

This might work for you (GNU sed):

sed = file | sed 'N;s/\(.*\)\n\(.*\)/[func (func (func \1)) [\2]/'

This inserts the line number into the output stream (Stdout) and then uses a second invocation of sed to pair it to its line and output the required string.

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