How can make a loop for sed in bash?

perrfect

New Member
Joined
Feb 19, 2020
Messages
2
Reaction score
0
Credits
0
Hi.
I need help with loop for sed.
I have the script:

Code:
cat test1.txt | sed -n 1,3p  | jq -Rn \

    --arg v1 / \

    --arg v3 server1 \

    '[inputs] | map({"{#NAME}" : $v1, "{#LIST}": ., "{#MARK}": $v3}) | { "data": . }'


cat test1.txt | sed -n 4,6p  | jq -Rn \

    --arg v1 / \

    --arg v3 server1 \

    '[inputs] | map({"{#NAME}" : $v1, "{#LIST}": ., "{#MARK}": $v3}) | { "data": . }'


cat test1.txt | sed -n 7,9p  | jq -Rn \

    --arg v1 / \

    --arg v3 server1 \

    '[inputs] | map({"{#NAME}" : $v1, "{#LIST}": ., "{#MARK}": $v3}) | { "data": . }'

How can create loop for this?
The file - "test.txt" can contain 100 or more lines.
Thank you.
 


I've never actually tried to use a loop in sed.

I've tried looking at my few ebooks on sed and racked my brains and I can't come up with anything. Perhaps this is a task better suited for awk?

Or thinking laterally - maybe the paste command can help here?
Paste can join multiple lines together.
And seeing as you're using sed to read three lines at a time from the file, perhaps something like this is what you're looking for:
Bash:
cat test1.txt | paste -d '\t' - - - | while read line; do
    echo $line | jq -Rn --arg v1 /\
    --arg v3 server1 \
    '[inputs] | map({"{#NAME}" : $v1, "{#LIST}": ., "{#MARK}": $v3}) | { "data": . }'
done

test1.txt is piped to the paste command, which joins the output together 3 lines at a time, using tabs to delimit each line.
Each set of 3 conjoined lines are then read into a variable, which is echoed and piped to your jq command.

That way you should be able to process the entire file using one long piped command. No need for any loops in sed, just one simple while loop in the shell. AND you're only catting the input file once, instead of multiple times.

NOTE: I don't have the jq utility installed on my machine - I also don't have your test-file. So I'm completely unable to test this.
But I don't see any reason why it shouldn't work. Unless I've made a typo or two in there?!
 
Last edited:
I guess I'm the weird one that likes sed. :)
In any case Jas is right. sed is a "streaming" editor. Better at search/replace than
joining 3 files.
 
I guess I'm the weird one that likes sed. :)
In any case Jas is right. sed is a "streaming" editor. Better at search/replace than
joining 3 files.

Nobody said anything about disliking sed. I like sed and use it rather a lot. It's an extremely useful tool. But in this case, I just didn't think it was the correct tool for the job! :D
 

Members online


Latest posts

Top