Tuesday, February 6, 2024

[SOLVED] How to use cut a string including whitespace

Issue

I'm working on a little Bash script where I need to cut a line into several variables.

Here's an example of the line to cut:

00577APP01     REC1_005 R_ESP01_R_TPP2SJAPPCB1

I've written this for now:

CDSOC=$(echo "${line}" | cut -c1-5)
CDAPP=$(echo "${line}" | cut -c6-15)
IDEXT=$(echo "${line}" | cut -c16-)

However, as you can see, the IDEXT in our example is:

REC1_005 R_ESP01_R_TPP2SJAPPCB1

I'd like to get it back in one piece, but the cut stops at the white space and doesn't continue.

What can I do so that it takes it all?


Solution

You'll probably need to replace multiple spaces with a single space using Bash before. In order to translate or delete characters you could use tr --squeeze-repeats

"replace each sequence of a repeated character that is listed in the last specified ARRAY, with a single occurrence of that character"

tr -s ' '

Then, further processing can be done on --fieds | -f

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

echo "00577APP01     REC1_005 R_ESP01_R_TPP2SJAPPCB1" | tr -s ' ' | cut -d ' ' -f 2-
REC1_005 R_ESP01_R_TPP2SJAPPCB1


Answered By - U880D
Answer Checked By - Senaida (WPSolving Volunteer)