I have a pipe-delimited file that has 1 or more leading spaces. Do you know how to remove these leading spaces, using AWK, while I'm proceesing the file?
Assuming you want to remove all spaces from the line, you can use the gsub function in nawk.
nawk -F"|" '{gsub(" ","",$0);print $1,$2,$3,$4}' filename
Thx grega. I do not want to delete all spaces, just the leading spaces. Some of the fields will have name (|first <space> last|) and address. So only leading spaces will be deleted.
sed "s/\(|\) */\1/" filename works for me, Thanks.
Could you please explain it in English. I know that it removes leading spaces that immediately follow a pipe, but what does each piece following sed"s/ mean?
The \( \) pair save everything between them (in this case just the vertical bar) in register 1, which is replayed in the substitution by the \1. An asterisk following a character matches any number of that character so the blank asterisk matches any number of blanks.
gsub() function isn't avaible in original version of awk, so I must write a bunch of code:
BEGIN { FS = "|" }
{
# removing leading spaces
for (i = 1; i <= NF; i ++) { # any field of input line
n = split($i, ch, " "
for (j = 1; j <= n; j ++) { # any word of the field
if (j == 1)
newFld = ch[j]
else
newFld = newFld " " ch[j]
}
if (newLn == ""
newLn = newFld
else
newLn = newLn FS newFld
}
# Contens of the variable "newLn" is without leading spaces
# in the fields.
# Here is posible to process the contens
# of the variable "newLn" (instead "print newLn".
print newLn
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.