Ask Your Question
1

Cut command is not working as expected.

asked 2018-03-08 22:37:14 -0600

updated 2018-05-31 05:37:04 -0600

FranciscoD_ gravatar image

I wanted to make a text file named "sample.txt" & inside in it I wanted to write 'The quick brown; fox jumps over the lazy dog' So I typed this command

"echo 'The quick brown; fox jumps over the lazy dog' > sample.txt"

To extract contents by a list of characters I typed this

"cut -c 5 sample.txt" This outputs the 5th character "q",

To extract the contents by a field, I typed this

"cut -f 2 sample.txt"

I should see "dog" as output. But this is not working as expected. Here is the code

[root@localhost TEST]# echo 'The quick brown; fox jumps over the lazy dog' > sample.txt

[root@localhost TEST]# cat sample.txt

The quick brown; fox jumps over the lazy dog

[root@localhost TEST]# cut -c 5 sample.txt

q [root@localhost TEST]# cut -f 2 sample.txt

The quick brown; fox jumps over the lazy dog

[root@localhost TEST]

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
4

answered 2018-03-08 23:25:05 -0600

You have to specify a delimiter for the field separation. The default delimiter is Tab and from man cut.

-f, --fields=LIST
select  only  these  fields;   also  print any line that contains no delimiter character, unless the -s option is specified

So, as your sample.txt does not include a Tab the whole line is printed. If you add -s to your command, nothing would be printed.

To get the second field of your sample.txt as it is, use the command as follows.

cut -d ' ' -f 2 sample.txt

But I am still wondering why you would expect dog to be printed.

To use the default delimiter Tab you would have to generate the file as follows to add Tab delimiters between the words.

echo -e 'The\tquick\tbrown;\tfox\tjumps\tover\tthe\tlazy\tdog' > sample.txt
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2018-03-08 22:37:14 -0600

Seen: 131 times

Last updated: Mar 08