如何在Bash中使用for循环将文本文件中的一行字符串作为分隔变量传递给另一个脚本。
如何在Bash中使用for循环将文本文件中的一行字符串作为分隔变量传递给另一个脚本。
这个问题已经有了答案:
我正在编写一个接受 manifest.txt
文件的Bash脚本。它应该循环遍历该文本文件的每一行,并调用另一个脚本来通过空格分隔符分离文本行的文本字符串。
我卡在了如何拆分文本字符串的问题上;我尝试使用 cut -d\' \'
,但这对我没有起作用。
以下是文本文件的示例:
20200451310 B.315 30203131340 Pam 3781, no.1 20200461200 B.16 20200471180 B.116, B.198 20200471190 B.129 10107291410 B.102 30203141220 Pam 3870, no. 1 20200481160 B.525
这是我目前拥有的Bash脚本:
#!/bin/bash IFS=$'\n' # make newlines the only separator set -f # disable globbing for i in $(cat < "${manifest.txt}"); do echo " $i" uid = ${i | cut -d' ' -f1} string = ${i | cut -d' ' -f2-10} echo "uid is ${uid}" echo "string is ${string}" /anotherscript.sh ${uid} ${string} done
结果例子应该是:
/anotherscript.sh "30203141220" "Pam 3870, no. 1"
admin 更改状态以发布 2023年5月21日
你可以简化你的脚本:
#!/usr/bin/env bash while read -r uid string; do ./anotherscript.sh "$uid" "$string" done < manifest.txt
你的尝试中有一堆错误:
"${manifest.txt}"
尝试在manifest.txt
上进行变量扩展,但它不是一个变量名,导致出现错误;你应该使用manifest.txt
cat < somefile
可以简化为cat somefile
- 在 Bash 中,
for i in $(cat somefile)
可以简化为for i in $(< somefile)
-
但实际上,你想要读取行:
read IFS= read -r i; do ...; done < manifest.txt
-
i | cut -d' ' -f1
不会让cut
读取$i
;你需要使用类似cut -d' ' -f1 <<< "$i"
的东西代替 ${somecommand}
是错误的语法;对于命令替换,你应该使用$(somecommand)
- 赋值语句中不能有等号周围的空格:
uid = something
应该改为uid=something
-
为了分割一个字符串,使用
read
读取多个变量,不要使用cut
:while read -r uid string; do ... done < manifest.txt
-
/anotherscript.sh
可能是错误的路径,应该改为./anotherscript.sh
-
/anotherscript.sh ${uid} ${string}
中的参数应该被引用:./anotherscript.sh "$uid" "$string"