击:读线由行的文件,并处理每个段为参数,其他PROG [英] Bash: read a file line-by-line and process each segment as parameters to other prog
问题描述
我有一些肮脏的工作要做,所以Bash脚本似乎是一个不错的选择。我是新来猛砸,并经历让我有种受挫。
I have some dirty work to do, so a Bash script seems to be a good choice. I'm new to Bash, and the experience makes me kind of frustrated.
该文件mapfiles.txt由线如下的。每一行都有一个空格分隔四个部分。每段再presents一个输入参数的外部程序名前卫。例如,cm19_1.png是在文件名,0001在首页,121422481在经度和31035995的纬度
The file mapfiles.txt consists of lines as follow. Each line has four segments separated by a white space. Each segment represents a input parameter to an external program name 'prog'. For example, "cm19_1.png" is the filename, "0001" the index, "121422481" the longitude, and "31035995" the latitude.
文件:mapfiles.txt
File: mapfiles.txt
cm19_1.png 0001 121422481 31035995
cm19_2.png 0002 121423224 31035995
cm19_3.png 0003 121423967 31035995
…
我要执行类似的命令到每一行。正如下面显示的PROG的输入参数顺序略有不同。因此,它是有道理写一个bash脚本来处理重复的工作。
I want to execute similar commands to each line. As show below, the prog's input parameter order is slightly different. So it makes sense to write a bash script to handle the repeated work.
[Usage] prog <index> <longitude> <latitude> <filename>
example: prog 0001 121422481 31035995 cm19_1.png
一般情况下,bash脚本会以这种方式进行操作:
Generally, the bash script will operate in this way:
- 阅读从mapfiles.txt一行
- 分割段
- 用正确的参数顺序调用PROG
下面来run.sh。
#!/bin/sh
input=mapfiles.txt
cmd=prog
while read line
do
file=$(echo $line | cut -d' ' -f1)
key=$(echo $line | cut -d' ' -f2)
log=$(echo $line | cut -d' ' -f3)
lat=$(echo $line | cut -d' ' -f4)
echo $cmd $key $log $lat $file
done < "$input"
我所期待的是
prog 0001 121422481 31035995 cm19_1.png
prog 0002 121423224 31035995 cm19_2.png
prog 0003 121423967 31035995 cm19_3.png
…
实际结果我是
cm19_1.png21422481 31035995
cm19_2.png21423224 31035995
cm19_3.png21423967 31035995
这是我感到困惑的问题。
Problems that confused me
- 哪里是'前卫'?
- 哪里是空白?
- 这有什么错参数顺序?
嗯...我写我的Mac上使用vim这个脚本,并将其复制到一个科学的Linux机器和Gentoo系统。这三个家伙得到同样荒谬的输出。
Hmm… I wrote this script on my Mac using vim and copy it to a Scientific Linux box and a gentoo box. These three guys get the same ridiculous outputs.
推荐答案
您可以简化这个有很多:
You can simplify this a lot:
while read file key log lat
do
echo $cmd $key $log $lat $file
done < "$input"
这篇关于击:读线由行的文件,并处理每个段为参数,其他PROG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!