在bash

时间:2018-01-03 02:30:01

标签: bash

我一直在使用bash,需要创建一个字符串参数。 bash对我来说是个新鲜事,我不知道如何从列表中构建bash中的字符串。

// foo.txt是abs文件名列表。

/foo/bar/a.txt
/foo/bar/b.txt
/delta/test/b.txt

应该变成:a.txt,b.txt,b.txt

OR:/foo/bar/a.txt,/foo/bar/b.txt,/delta/test/b.txt

s = ""
for file in $(cat foo.txt);
do
    #what goes here?    s += $file  ?
done

myShellScript --script $s

我认为有一种简单的方法可以做到这一点。

3 个答案:

答案 0 :(得分:1)

这似乎有效:

#!/bin/bash
input="foo.txt"
while IFS= read -r var
  do
  basename $var >> tmp
  done < "$input"
paste -d, -s tmp > result.txt

输出:a.txt,b.txt,b.txt

basename为您提供所需的文件名,粘贴将按照您似乎需要的顺序放置它们。

答案 1 :(得分:1)

with for循环:

for file in $(cat foo.txt);do echo -n "$file",;done|sed 's/,$/\n/g'

用tr:

cat foo.txt|tr '\n' ','|sed 's/,$/\n/g'

只有sed:

sed ':a;N;$!ba;s/\n/,/g' foo.txt

答案 2 :(得分:0)

输入字段分隔符可与set一起使用以创建拆分/加入功能:

# split the lines of foo.txt into positional parameters
IFS=$'\n'
set $(< foo.txt)

# join with commas
IFS=,
echo "$*"

仅对文件名,添加一些sed:

IFS=$'\n'; set $(sed 's|.*/||' foo.txt); IFS=,; echo "$*"