【发布时间】:2015-09-12 04:08:13
【问题描述】:
我需要将一个文件中的多行作为一个逗号分隔的参数传递到脚本中。每当我尝试使用将文件处理为单个字符串的输出时,逗号就会成为分隔符。我该怎么做?
测试用例:
[user@host]$ #Here is a word list, my target words are on lines starting with "1,"
[user@host]$ cat word_list_numbered.txt
1,lakin
2,chesterfield
3,sparkplug
4,unscrawling
5,sukkah
1,girding
2,gripeful
3,historied
4,hypoglossal
5,nonmathematician
1,instructorship
2,loller
3,containerized
4,duodecimally
5,oligocythemia
1,nonsegregation
2,expecter
3,enterrologist
4,tromometry
5,salvia
[user@host]$ #Here is a mock operation, it just outputs the number of args, I want all selected words as one argument
[user@host]$ cat operation.sh
echo "This script has $# arguments"
[user@host]$ #Here is a script that outputs the needed words as comma delimited
[user@host]$ grep '^1,' word_list_numbered.txt | tr -d '1,' | tr '\n' ',' | sed 's/,$//' lakin,girding,instructorship,nonsegregation[user@host]$
[user@host]$ #Here is the operation script receiving that comma delimited list
[user@host]$ ./operation.sh $(grep '^1,' word_list_numbered.txt | tr -d '1,' | tr '\n' ',' | sed 's/,$//')
This script has 4 arguments
[user@host]$ #oops, too many arguments
[user@host]$ ./operation.sh foo,bar
This script has 1 arguments
[user@host]$ ./operation.sh foo bar
This script has 2 arguments
[user@host]$
详情:
- 需要的单词在以 1 开头的行中,
- 所有单词都应作为一个逗号分隔的参数传递给 operation.sh
- 我无法控制 word_list_numbered.txt 的格式,也无法控制 operation.sh 将所有单词作为一个逗号分隔的参数
- 多次运行 operation.sh 并不是最佳选择——我在问这个问题,所以我不必这样做
【问题讨论】:
-
您的 foo,bar 测试似乎涵盖了这种可能性,但由于我无法重现这一点,您系统上的
$IFS的值是多少? -
@swornabsent 是的,我确实走上了 $IFS 路线。它显然设置为换行符:
-
@msw 我正在尝试:选择以“1”开头的所有行中的单词;将它们用逗号分隔;将它们用作 operation.sh 的参数
-
为什么这里的每个答案都投了反对票?