简体   繁体   English

Shell脚本执行循环

[英]shell scripting do loop

Sorry Im new to unix, but just wondering is there anyway I can make the following code into a loop. 对不起,我是unix的新手,但是我想知道是否仍然可以将以下代码放入循环中。 For example the file name would change every time from 1 to 50 例如,文件名每次都会从1更改为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. 我想将其变成一个循环,其中cd1_abcd_w.txt然后将变成cd2_abcd_w.txt,输出将是cd2_rightformat.txt等...一直到50。所以基本上是cd $ i。

Many thanks 非常感谢

In bash , you can use brace expansion: bash ,可以使用大括号扩展:

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. for i = 1 to 10循环的BASIC相似,两端包含在内,该循环将输出数字1到10。

You then just replace the echo command with whatever you need to do, such as: 然后,您只需将echo命令替换为您需要执行的操作即可,例如:

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. 如果您需要小于10的数字前导零,请将for循环中的表达式更改for {01..50} 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 ). (相当于for i = 1 to 50 step 9的BASIC)。

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: 这将在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM