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?
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?
Explanation:
-e
- denotes a command to be executed:a
- is a label/$/N
- defines the scope of the match for the current and the (N)ext lines/\n/\\n/;
- replaces all EOL with\n
ta;
- goto label a if the match is successfulTaken from my blog.
It looks like the answers already exist.
If you want
a, b, c
format, usels -m
( Tulains Córdova’s answer)Or if you want
a b c
format, usels | xargs
(simpified version of Chris J’s answer)Or if you want any other delimiter like
|
, usels | paste -sd'|'
(application of Artem’s answer)just bash
Similar to the very first option but omits the trailing delimiter
The sed way,
Note:
This is linear in complexity, substituting only once after all lines are appended into sed's Pattern Space.
@AnandRajaseka's answer, and some other similar answers, such as here, are O(n²), because sed has to do substitute every time a new line is appended into the Pattern Space.
To compare,
ls
has the option-m
to delimit the output with", "
a comma and a space.piping this result to
tr
to remove either the space or the comma will allow you to pipe the result again totr
to replace the delimiter.in my example i replace the delimiter
,
with the delimiter;
replace
;
with whatever one character delimiter you prefer since tr only accounts for the first character in the strings you pass in as arguments.