How to send parameters on AWK to replace a parameter. Unix Korn Shell - shell

I'm trying to replace a parameter to change a value when the AWK is used to search for a string in a file.
is this possible? I'm doing this.
DisplayMessage()
{
##Parameter 1 = Message ID.
MessageFile="/dev/fs/C/Users/salasfri/Desktop/Messages.txt"
Message=$(awk '$1 ~ /^'$MessageID'$/ {$1=""; print $0}' $MessageFile)
}
the Message File looks for this in the file "MessageFile":
0005 The file ${1} was not tranmitted.
it search for 0005 and get the message "The file ${1} was not tranmitted."
I want to replace ${1} with the name of the file
this could be possible with awk? any idea?

this should do...
awk '$1~/^'$MessageID'$/ {$1=""; sub("\\${1}",FILENAME); print}'
but perhaps you want to change to
awk -v mid="${MessageID}" '$1==mid {$1=""; sub("\\${1}",FILENAME); print}'
since you're looking for an exact match, not pattern match. Also better to use awk variables instead of quote dance.

Related

echo specific string inside quotes from variable

I need a script that echo one of strings wrapped in quotes.
For example, from variable x="C. Ronaldo" "dos Santos Aveiro" "Cristiano Ronaldo" i want to echo the third one.
So I want to get output like: "Cristiano Ronaldo"
I've tried it with echo $x | awk '{print $3}' but it gives me "dos..
Any help?
By default awk splits records by spaces into fields, given your string, "dos is the third field. To parse this string the way you desire GNU awk's FPAT is required. E.g:
awk -v FPAT='"[^"]*"' '{print $3}'

Read variable from file with awk?

I'm new using awk and I found it very useful for extracting data from columns. For example in my file I had
Data: 1234 23434 31324
If I wanted the second column I used:
awk '/Data:/ {print $3}' file.txt
But next, I had some variables inside the file, let's say:
variable_1=1
variable_2=4
How can I extract only the value? how can I extract the name of the variable by knowing the value?
awk offers to specify the field delimiter:
awk -F'=' '$1 == "variable_1" {print $2}' file
Prints:
1
You can do a lot of things with your file, what do you really want?
Get values:
source file.txt
echo "variable_1=${variable_1}"
echo "variable_2=${variable_2}"
Get keys corresponding to value 2
sed '/=2$/ s/=.*//' file.txt

How to save the name of the file if it is being treated in the script

I have 88 folders, each of which contains the file "pair.'numbers'." (pair.3472, pair.7829 and so on). I need to treat the files with awk to extract the second column, but I need to save the numbers. If I try:
#!/bin/bash
for i in {1..88}; do
awk '{print $2}' ~/Documents/attempt.$i/pair* > ~/Results/pred.pair*
done
It doesn't save the numbers, but gives only one file: pred.pair*
Thanks for any tips.
You don't need a loop (and see https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice for why that's a Good Thing):
awk '
FNR==1 { close(out); out=FILENAME; sub(/\/Documents.*\//,"/Results/pred.",out) }
{ print $2 > out }
' ~/Documents/attempt.{1..88}/pair*
#!/bin/bash
for i in {1..88}; do
awk '{fname=FILENAME;sub(".*/", "", fname);print $2 > ("~/Results/pred."fname)}' ~/Documents/attempt.$i/pair*
done
Use AWK build in variable FILENAME. We need to get the basename fname from FILENAME. Then redirect $2 value to "~/Results/pred."fname
There are several ways to do it: awk has a FILENAME variable and you can redirect the output from within your awk script to a manipulated string which is based on FILENAME.
Or you can do it with bash
for i in {1..88}; do
to_be_processed_fname=$(ls ~/Documents/attempt.$i/pair*)
extension="${to_be_processed_fname/*./}"
awk '{print $2}' "${to_be_processed_fname}" > "$HOME/Results/pred.${extension}"
done
Now the above of course fails if you have more than one pair* files within the same directory. But I'm leaving that to you.

Bash - extract file name and extension from a string

Here is grep command:
grep "%SWFPATH%/plugins/" filename
And its output:
set(hotspot[hs_bg_%2].url,%SWFPATH%/plugins/textfield.swf);
set(hotspot[hs_%2].url,%SWFPATH%/plugins/textfield.swf);
url="%SWFPATH%/plugins/textfield.swf"
url="%SWFPATH%/plugins/scrollarea.swf"
alturl="%SWFPATH%/plugins/scrollarea.js"
url="%SWFPATH%/plugins/textfield.swf"
I'd like to generate a file containing the names of the all files in the 'plugins/' directory, that are mentioned in a certain file.
Basically I need to extract the file name and the extension from every line.
I can manage to delete any duplicates but I can't figure out how to extract the information that I need.
This would be the content of the file that I would like to get:
textfield.swf
scrollarea.swf
strollarea.js
Thanks!!!
PS: The thread "Extract filename and extension in bash (14 answers)" explains how to get filename and extension from a 'variable'. What I'm trying to achieve is extracting these from a 'file', which is completely different'
Using awk:
grep "%SWFPATH%/plugins/" filename | \
awk '{ match($0, /plugins\/([^\/[:space:]]+)\.([[:alnum:]]+)/,submatch);
print "filename:"submatch[1];
print "extension:"submatch[2];
}'
Some explanation:
the match function takes every line processed by awk (indicated by $0) and looks for matches to that regex. Submatches (the parts of the string that match the parts of the regex between parentheses) are saved in the array submatch. print is as straightforward as it looks, it just prints stuff.
For this specific problem
awk '/\/plugins\// {sub(/.*\//, ""); sub(/(\);|")?$/, "");
arr[$0] = $0} END {for (i in arr) print arr[i]}' filename
Use awk to simply extract the filename and then sed to clean up the trailing )"; characters.
awk -F/ '{print $NF}' a | sed -e 's/);//' -e 's/"$//'

awk function printing..... -bash?

For some reason that i'm trying to figure out i'm getting "-bash" printed out of this script:
cat sample | awk -v al=$0 -F"|" '{n = split(al, a, "|")} {print a[1]}'
the 'sample' file contains psv "pipe separated value", like a|b|c|d|e|f|d.
My intention is to use an array.
The result of the above script is an array of length 1 and th only item contained is "-bash", the name of the shell.
$0 by default points to the program that is currently used, but as far as i know, within an awk script, the $0 parameter 'should' point to the entire line being read.
since i would like to understand where the problem exaclty is "i'm new to bash/awk"
can you point me out which of the following steps is failing?
1-"concatenate" the sample file and pass it as input for the awk script
2-define a variable named 'al' with as value each line contained in 'sample'
3-define a pipe "|" as field separator
4-define an action, split the value of 'al' into an array named 'a' using a pipe as splitter
5-define another action, which in this case is simply printing the first item in the array
Any advice? thank you!
The $0 is expanded by the shell before it runs awk, and $0 is the name of the current program, which is bash, the - at the start is because bash was run by login(1) (see the description of the exec builtin in man bash)
You need to quote the $0 so the shell doesn't expand it, and awk sees it:
awk -v 'al=$0' -F"|" '{n = split(al, a, "|")} {print a[1]}' sample
But variable assignments are processed before reading any data, so that sets the variable al to the string "$0" at the start of the program, it does not set al to the contents of each input record.
If you want the record, just say so instead of using a variable:
awk -F"|" '{n = split($0, a, "|")} {print a[1]}' sample
By -v a1=$0, you are setting a1 to the name of the current programme, which is bash. See Arguments in man bash.
Err...
awk -F'|' '{ print $1 }' sample

Resources