-1

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

Allexj
  • 241
  • 1
  • 9
  • 2
    I doubt that the professor is right: `cut` can remove a fixed number of spaces only. – U. Windl Mar 07 '22 at 12:25
  • 1
    Cross-posted: https://stackoverflow.com/questions/71380920/how-to-use-cut-to-trim-the-first-x-variable-spaces – JRFerguson Mar 07 '22 at 12:33
  • Does this answer your question? [How do I trim leading and trailing whitespace from each line of some output?](https://unix.stackexchange.com/questions/102008/how-do-i-trim-leading-and-trailing-whitespace-from-each-line-of-some-output) – Wiktor Stribiżew Mar 07 '22 at 12:34
  • @WiktorStribiżew nope, because I also need the numbers, and that way I erase the numbers :/ – Allexj Mar 07 '22 at 12:37
  • I have found an answer myself: https://unix.stackexchange.com/a/693283/314643 – Allexj Mar 07 '22 at 13:51

3 Answers3

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!

Allexj
  • 241
  • 1
  • 9
0

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-
pLumo
  • 22,231
  • 2
  • 41
  • 66
  • thanks for answer, I wanted to only use cut though. I found an answer, if you are interested: https://unix.stackexchange.com/a/693283/314643 – Allexj Mar 07 '22 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. – pLumo Mar 07 '22 at 13:55
  • @Allexj You can't use only `cut` to remove a variable amount of spaces. – Kusalananda Mar 07 '22 at 14:51
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.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936