store cut command in shell variable

How to Store Output of Cut Command in variable in Unix

In Linux, cut is a useful command to extract sections and columns from input data, which you can pass as string, or files. It is available on almost every Linux distribution by default. But sometimes you may need to store output of cut command in variable in Unix. Here are the steps to do it.

How to Store Output of Cut Command in variable in Unix

Here is how to save output of cut command in variable in Unix. Let us say you want to cut column 2 from file data.txt. Here is the command for it.

$ cat data.txt
good morning
good evening
good night

$ cut -d " "-f 2 data.txt

In the above command, we use -d option to specify the delimiter ” ” and use -f option to specify that we want column #2. This way cut command will display the 2nd word on each line of your input file.

Now if you want to store the output of above cut command in a variable, just wrap the above command in $(…) as shown below.

$ list= $(cut -d " "-f 2 data.txt)
$ echo "$list"

As you can see, $list variable stores the 2nd column of your data.txt file, extracted using cut command. It is important to note that when you use echo command to view the value of your shell variable, you need to enclose it in double quotes. Only then it properly splits the data using whitespaces and newlines, as present in data.txt. If you directly call echo command on $list, it will print the entire output on single line without formatting it properly.

$ echo $list
morning evening night

Similarly, you can store any cut command’s output to shell variable. Here is the command to store the 6th character of each line in data.txt file.

$ list=$(cut -c 6 data.txt)
$ echo "$list"

Storing cut command’s output in shell variable is useful if you want to repeatedly use the output without running the entire command again. it is also useful if you want to process the output further.

In this short article, we have learnt how to store output of cut command in shell variable.

Also read:

How to Use Shell Variables in Awk Script
How to Setup SSH Keys in Linux
How to Create Nested Directories in Python
How to Find Package for File in Ubuntu
How to Prompt User for Input in Shell Script

Leave a Reply

Your email address will not be published.