-3

I need to read up until a delimiter and exclude the first character and take the value and put it into a variable. The first field in the line can be varying length which is why I can't use a standard cut or other methods I am familiar with. How do I read up until the "|" delimiter and exclude the first character?

T1000|||||||||||||||

I need a variable to contain the 1000 which would exclude the first character of "T". Also the value will not always be a static 4 length so need it to read dynamically.

  • 2
    You're conflating several different things -- an ideal StackOverflow question asks only *one* question, so "how do I remove a prefix from a string in bash?" should be searched for separately (saying "searched for" rather than "asked" because it very much is already in our knowledgebase). – Charles Duffy Apr 05 '19 at 21:47
  • 2
    Also, do you really want to stop *reading* at the first `|` (so the next read operation will begin just after it), or do you just need to *discard everything after* the `|`? If the former, you have https://stackoverflow.com/questions/10931915/how-can-i-read-words-instead-of-lines-from-a-file, except that you want to use a `|` rather than a space. If the latter, you have https://stackoverflow.com/questions/27500692/split-string-in-shell-script-while-reading-from-file or https://stackoverflow.com/questions/10586153/split-string-into-an-array-in-bash/31405855 – Charles Duffy Apr 05 '19 at 21:49
  • 1
    BTW, `cut` can be used perfectly well without knowing length; `cut -d'|' -f1` and there you are. That said, startup costs to `fork()` and `execve()` an instance of `cut` make it wildly inefficient compared to shell builtins (when not operating over a large enough quantity of data to amortize those costs), so it's best avoided anyhow. – Charles Duffy Apr 05 '19 at 22:02

2 Answers2

1

The -d argument to read overrides its default use of a newline as the delimiter that terminates the read.

Thus:

IFS= read -r -d '|' firstCol      # see http://mywiki.wooledge.org/BashFAQ/001
firstColWithoutT="${firstCol#T}"  # see https://wiki.bash-hackers.org/syntax/pe
printf '%s\n' "$firstColWithoutT" # see http://mywiki.wooledge.org/BashPitfalls#echo_.24foo
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0
txt="T1000|||||||||||||||"
var=$(echo ${txt: 1} | cut -d "|" -f1)

echo "$var"