1

I have been working in bash, and need to create a string argument. bash is a newish for me, to the point that I dont know how to build a string in bash from a list.

// foo.txt is a list of abs file names.

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

should turn into: a.txt,b.txt,b.txt

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

code

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

myShellScript --script $s

I figure there was an easy way to do this.

Fallenreaper
  • 10,222
  • 12
  • 66
  • 129

3 Answers3

1

This seems to work:

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

output: a.txt,b.txt,b.txt

basename gets you the file names you need and paste will put them in the order you seem to need.

farhang
  • 407
  • 1
  • 5
  • 13
1

with for loop:

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

with tr:

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

only sed:

sed ':a;N;$!ba;s/\n/,/g' foo.txt
once
  • 1,369
  • 4
  • 22
  • 32
0

The input field separator can be used with set to create split/join functionality:

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

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

For just the file names, add some sed:

IFS=$'\n'; set $(sed 's|.*/||' foo.txt); IFS=,; echo "$*"
Cole Tierney
  • 9,571
  • 1
  • 27
  • 35