Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to concatenate a string to each line of ls command output in unix

Tags:

shell

unix

I am a beginer in Shell script. Below is my requirement in UNIX Korn Shell.

Example:

When we list files using ls command redirect to a file the file names will be stored as below.

$ ls FILE*>FLIST.TXT
$ cat FLIST.TXT
FILE1
FILE2
FILE3

But I need output as below with a prefixed constant string STR,:

$ cat FLIST.TXT
STR,FILE1
STR,FILE2
STR,FILE3

Please let me what should be the ls command to acheive this output.

like image 860
TechVolcano Avatar asked May 25 '15 05:05

TechVolcano


People also ask

How do I concatenate a string in a Linux script?

The += Operator in Bash Bash is a widely used shell in Linux, and it supports the '+=' operator to concatenate two variables. As the example above shows, in Bash, we can easily use the += operator to concatenate string variables.

How do I concatenate strings in terminal?

This can be done with shell scripting using two methods: using the += operator, or simply writing strings one after the other. The examples below show some shell scripts that can be used to concatenate strings. Example 1: In this example, we will concatenate two strings using += operator.

Does the ls command provide output?

Long Listing Format. The default output of the ls command shows only the names of the files and directories, which is not very informative. The -l ( lowercase L) option tells ls to print files in a long listing format.


2 Answers

You can't use ls alone to append data before each file. ls exists to list files.
You will need to use other tools along side ls.

You can append to the front of each line using the sed command:

cat FLIST.TXT | sed 's/^/STR,/'

This will send the changes to stdout.


If you'd like to change the actual file, run sed in place:

sed -i -e 's/^/STR,/' FLIST.TXT  

To do the append before writing to the file, pipe ls into sed:

ls FILE* | sed 's/^/STR,/' > FLIST.TXT
like image 158
Trevor Hickey Avatar answered Sep 19 '22 23:09

Trevor Hickey


The following should work:

ls FILE* | xargs -i echo "STR,{}" > FLIST.TXT

It takes every one of the file names filtered by ls and adds the "STR," prefix to it prior to the appending

like image 8
higuaro Avatar answered Sep 21 '22 23:09

higuaro