如何将ls -1的结果加入到一行中,并用我想要的任何内容将其分隔?


当前回答

如果你的xargs版本支持-d标志,那么这应该可以工作

ls  | xargs -d, -L 1 echo

-d是分隔符标志

如果没有-d,那么可以尝试以下操作

ls | xargs -I {} echo {}, | xargs echo

第一个xargs允许您指定分隔符,在本例中为逗号。

其他回答

如果你喜欢Python3,你可以这样做(但是请解释为什么你会这样做?):

ls -1 | python -c "import sys; print(','.join(sys.stdin.read().splitlines()))"

就bash

mystring=$(printf "%s|" *)
echo ${mystring%|}

用换行符替换最后一个逗号:

ls -1 | tr '\n' ',' | sed 's/,$/\n/'

Ls -m包含屏幕宽度字符处的换行符(例如第80行)。

主要是Bash(只有ls是外部的):

saveIFS=$IFS; IFS=$'\n'
files=($(ls -1))
IFS=,
list=${files[*]}
IFS=$saveIFS

在Bash 4中使用readarray(又名mapfile):

readarray -t files < <(ls -1)
saveIFS=$IFS
IFS=,
list=${files[*]}
IFS=$saveIFS

感谢gniourf_gniourf的建议。

一般不建议解析ls,所以另一种更好的方法是使用find,例如:

find . -type f -print0 | tr '\0' ','

或者使用find和粘贴:

find . -type f | paste -d, -s

对于一般的多行连接(与文件系统无关),请检查:Unix命令行上简明而可移植的“join”。

sed方法,

sed -e ':a; N; $!ba; s/\n/,/g'
  # :a         # label called 'a'
  # N          # append next line into Pattern Space (see info sed)
  # $!ba       # if it's the last line ($) do not (!) jump to (b) label :a (a) - break loop
  # s/\n/,/g   # any substitution you want

注意:

这在复杂度上是线性的,在所有行都附加到sed的模式空间之后只替换一次。

@AnandRajaseka的答案,和其他一些类似的答案,比如这里,是O(n²),因为sed必须做替换每次新行追加到模式空间。

来比较,

seq 1 100000 | sed ':a; N; $!ba; s/\n/,/g' | head -c 80
  # linear, in less than 0.1s
seq 1 100000 | sed ':a; /$/N; s/\n/,/; ta' | head -c 80
  # quadratic, hung