How to join multiple lines of file names into one

2019-01-04 05:08发布

I would like to join the result of ls -1 into one line and delimit it with whatever i want.

Are there any standard Linux commands I can use to achieve this?

19条回答
Evening l夕情丶
2楼-- · 2019-01-04 05:12

You can use chomp to merge multiple line in single line:

perl -e 'while (<>) { if (/\$/ ) { chomp; } print ;}' bad0 >test

put line break condition in if statement.It can be special character or any delimiter.

查看更多
SAY GOODBYE
3楼-- · 2019-01-04 05:13

Don't reinvent the wheel.

ls -m

It does exactly that.

查看更多
疯言疯语
4楼-- · 2019-01-04 05:13

If you version of xargs supports the -d flag then this should work

ls  | xargs -d, -L 1 echo

-d is the delimiter flag

If you do not have -d, then you can try the following

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

The first xargs allows you to specify your delimiter which is a comma in this example.

查看更多
聊天终结者
5楼-- · 2019-01-04 05:14

I think this one is awesome

ls -1 | awk 'ORS=","'

ORS is the "output record separator" so now your lines will be joined with a comma.

查看更多
三岁会撩人
6楼-- · 2019-01-04 05:14

The combination of setting IFS and use of "$*" can do what you want. I'm using a subshell so I don't interfere with this shell's $IFS

(set -- *; IFS=,; echo "$*")

To capture the output,

output=$(set -- *; IFS=,; echo "$*")
查看更多
相关推荐>>
7楼-- · 2019-01-04 05:16

ls produces one column output when connected to a pipe, so the -1 is redundant.

Here's another perl answer using the builtin join function which doesn't leave a trailing delimiter:

ls | perl -F'\n' -0777 -anE 'say join ",", @F'

The obscure -0777 makes perl read all the input before running the program.

sed alternative that doesn't leave a trailing delimiter

ls | sed '$!s/$/,/' | tr -d '\n'
查看更多
登录 后发表回答