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


当前回答

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

其他回答

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

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的建议。

这个命令是为PERL爱好者准备的:

ls -1 | perl -l40pe0

这里的40是空格的八进制ascii码。

-p将逐行处理并打印

-l将负责用我们提供的ASCII字符替换尾随的\n。

-e是通知PERL我们正在执行命令行。

0表示实际上没有命令要执行。

Perl -e0与Perl -e ' '相同

sed -e :a -e '/$/N; s/\n/\\n/; ta' [filename]

解释:

-e -表示要执行的命令 :a -为标签 /$/N -定义当前和(N)下一行的匹配范围 s / \ n / \ \ n /;-将所有EOL替换为\n 助教;-如果匹配成功,则标记a

摘自我的博客。

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

看起来答案已经存在了。

如果你愿意 a, b, c格式,使用ls -m (Tulains Córdova的答案)

或者如果你想要bc格式,使用ls | xargs (Chris J回答的简化版本)

或者如果你想要任何其他的分隔符,如|,使用ls |粘贴-sd'|' (Artem ' s answer的应用)