Sorry Im new to unix, but just wondering is there anyway I can make the following code into a loop. For example the file name would change every time from 1 to 50
My script is
cut -d ' ' -f5- cd1_abcd_w.txt > cd1_rightformat.txt ;
sed 's! \([^ ]\+\)\( \|$\)!\1 !g' cd1_rightformat.txt ;
sed -i 's/ //g' cd1_rightformat.txt;
cut -d ' ' -f1-4 cd1_abcd_w.txt > cd1_extrainfo.txt ;
I would like to make this into a loop where cd1_abcd_w.txt would then become cd2_abcd_w.txt and output would be cd2_rightformat.txt etc...all the way to 50. So essentially cd$i.
Many thanks
In bash
, you can use brace expansion:
for num in {1..10}; do
echo ${num}
done
Similar to a BASIC for i = 1 to 10
loop, it's inclusive at both ends, that loop will output the numbers 1 through 10.
You then just replace the echo
command with whatever you need to do, such as:
cut -d ' ' -f5- cd${num}_abcd_w.txt >cd${num}_rightformat.txt
# and so on
If you need the numbers less than ten to have a leading zero, change the expression in the for
loop to be {01..50}
instead. That doesn't appear to be the case here but it's very handy to know.
Also in the not-needed-but-handy-to-know category, you can also specify an increment if you don't want to use the default of one:
pax> for num in {1..50..9}; do echo ${num}; done
1
10
19
28
37
46
(equivalent to the BASIC for i = 1 to 50 step 9
).
This should work:
for((i=1;i<=50;i++));do
cut -d ' ' -f5- cd${i}_abcd_w.txt > cd${i}_rightformat.txt ;
sed 's! \([^ ]\+\)\( \|$\)!\1 !g' cd${i}_rightformat.txt ;
sed -i 's/ //g' cd${i}_rightformat.txt;
cut -d ' ' -f1-4 cd${i}_abcd_w.txt > cd${i}_extrainfo.txt ;
done
This would work in bash:
for in in $(seq 50)
do
cut -d ' ' -f5- cd$i_abcd_w.txt > cd$1_rightformat.txt;
sed 's! \([^ ]\+\)\( \|$\)!\1 !g' cd$i_rightformat.txt;
sed -i 's/ //g' cd$i_rightformat.txt;
cut -d ' ' -f1-4 cd$i_abcd_w.txt > cd$i_extrainfo.txt;
done
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.