Home > Enterprise >  Cut string from position to character
Cut string from position to character

Time:01-13

I'd like to cut a string from a number of position until a specific character "/" :

It would cut this line :

Export text H8X7IS5G.FIC NB regs COLOLO 4138/4138

To this one :

4138

What i tried is to use cut -c with the position and the character but of course it doesn't work :

cut -c 57-'/'

CodePudding user response:

If you want to stick with cut then this might be what you want:

echo 'Export text H8X7IS5G.FIC NB regs COLOLO 4138/4138' |
cut -c41- | cut -d/ -f1

There are many other ways to accomplish this task. If you have a grep which supports perl-compatible regular expressions, for instance, then I'd suggest something along this line:

grep -Po '.{40}\K[^/]*'

Or, a sed one-liner:

sed 's/.\{40\}//; s|/.*||'

Or, using pure bash

[[ $line =~ .{40}([^/]*) ]] && printf '%s\n' "${BASH_REMATCH[1]}"

CodePudding user response:

Assuming you're trying to process a single variable at a time (rather than a stream with hundreds or thousands of lines), you don't need cut for this at all.

input='Export text H8X7IS5G.FIC NB regs COLOLO 4138/4138'
result=${input:40}
echo "${result%%/*}"

...emits 4138.

Both ${var:start:len} (and its shorter synonym ${var:start}) and ${var%%PATTERN} are examples of parameter expansion syntax; the former takes only a subset of a string starting at a given position; the latter trims the longest possible match of PATTERN (${var%PATTERN} trims the shortest possible match of PATTERN instead).

These and other string manipulations in bash are also documented in BashFAQ #100.

CodePudding user response:

An awk way:

string="Export text H8X7IS5G.FIC NB regs COLOLO 4138/1234"

awk -F/ '{print substr($1,41)}' <<< "$string"

output:

4138
  •  Tags:  
  • Related