0

I have a file that is like this:

              67 lol
             143 hi
              21 test
               1 ciao
               5 lo

I want to remove the spaces.

67 lol
143 hi
21 test
1 ciao
5 lo

I know that I can use sed to do that, for example with:

cat ciao | sed 's/[[:space:]]*\([[:digit:]]* .*\)/\1/' | sort -g

but my professor says that I can easily use cut to do that... but I really don't know how.

Something like this:

cat ciao | rev | cut -d' ' -f1 | rev

would not work because I lose the number information. lol hi test ciao lo

5

3 Answers 3

1

If your file had a tab and not spaces, you could use cut only:

cut -f2- < file

With spaces, cut is not enough, but you can use a combination of tr and cut:

tr -s ' ' < file | cut -d' ' -f2-
3
  • thanks for answer, I wanted to only use cut though. I found an answer, if you are interested: unix.stackexchange.com/a/693283/314643 Commented Mar 7, 2022 at 13:50
  • 1
    "I wanted to only use cut only" and posts an answer that uses (a useless use of) cat, 2x rev and cut. I bet, tr + cut performs better. Commented Mar 7, 2022 at 13:55
  • @Allexj You can't use only cut to remove a variable amount of spaces. Commented Mar 7, 2022 at 14:51
1

I found an answer: I can do this:

cat ciao | rev | cut -d ' ' -f 1,2 | rev

to not lose the number information. works!

1
  • 2
    You will find that this fails if a line has more than the expected number of space-delimited words. Commented Mar 7, 2022 at 14:43
0

Consider that until your professor shows code that works, they may not know what they are talking about. The cut utility is a tool for extracting columns delimited by some single character. Your data is not that.

If all you want is to remove any spaces at the start of lines, then the following sed command will do that by matching zero or more spaces at the beginning of each line and removing them.

sed 's/^ *//' file

Using cut and rev is only possible if you know for a fact that you have no more spaces on any line than the initial ones and the single space between the number and the word, which you say nothing about. If you have a line saying 12 Abba Baab, that no longer holds.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.