Issue
For example, I have a file 'zz'.
wire [3:0] dcs_ctrl
And I want to print like this.
wire [3:0] dcs_ctrl0
wire [3:0] dcs_ctrl1
wire [3:0] dcs_ctrl2
wire [3:0] dcs_ctrl3
For this, I want to do the operation for the whole line (like print the whole line 4 times as following).
But when I do
for i in `cat zz`; do for j in {0..3}; do echo "$i"; done; done
I get:
wire
wire
wire
wire
[3:0]
[3:0]
[3:0]
[3:0]
dcs_ctrl
dcs_ctrl
dcs_ctrl
dcs_ctrl
So the for
loop has taken the space-separated words as separate arguments. How can I pass the whole line as an argument to the for loop body?
Solution
The default seperator in bash is space
, and you can set the default seperator to \n
with IFS=$'\n'
when you want do seperate by line.
$ cat zz
wire [3:0] dcs_ctrl
$ IFS=$'\n'; for i in `cat zz`; do for j in {0..3}; do echo "$i"; done; done
wire [3:0] dcs_ctrl
wire [3:0] dcs_ctrl
wire [3:0] dcs_ctrl
wire [3:0] dcs_ctrl
But this is not the prefered way, according to the comment below of Gordon Davisson.
You can use the while loop
instead, as the example in answer of mandy8055
while IFS= read -r line; do
for j in {0..3}; do
echo "$line"
done
done < zz
Refer to:
How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?
Why you don't read lines with "for"
Answered By - LF-DevJourney Answer Checked By - Mildred Charles (WPSolving Admin)