1

I have lines and want to do sed operation, on string which comes after it has read '|'character three times. How can I do this in Shell Script?

Input: aaaa|bbbbb|ccccc|hello

Desired Ouput: aaaa|bbbbb|ccccc|hel

This is be done on hello which is after three '|'

-> sed 's/({.3}).*/\1/g'

2 Answers 2

1

You don't specify what you want to do with the last field to transform "hello" into "hel". Here's one way:

sed -r 's/^(([^|]+\|){3})(...).*/\1\3/' file
  • ([^|]+\|) denotes a pipe delimited field (with the pipe)
  • (([^|]+\|){3}) denotes three such fields
    • requires sed's -r option
    • on OSX or BSD-ish implementations of sed, use -E instead)
  • I capture the next three characters with (...)
  • then replace all with the first and third set of capturing parentheses
Sign up to request clarification or add additional context in comments.

Comments

1

Use the cut command instead of sed:

$ echo "aaaa|bbbbb|ccccc|hello" | cut -d '|' -f 4
hello

1 Comment

I wish to make changes in the file itself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.