Top 100+ Sed (stream Editor) Interview Questions And Answers
Question 1. Write A Command To Replace The Word "awful" With "proper" In File?
Answer :
sed s/bad/proper/ < filename
Question 2. Write A Command To Replace The Word "horrific" With "proper" Globally In A File?
Answer :
sed s/horrific/correct/g < filename
Adobe Photoshop Interview Questions
Question three/four. Write A Command To Replace The Word "apple" With "(apple)" In A File?
Answer :
sed s/apple/(&)/ < filename
Adobe Photoshop Tutorial
Question 5. Write A Command To Switch The Two Consecutive Words "apple" And "mango" In A File?
Answer :
sed 's/(apple) (mango)/2 1/' < filename
Audio Editor Interview Questions
Question 6. Write A Command To Replace The Second Occurrence Of The Word "bat" With "ball" In A File?
Answer :
sed 's/bat/ball/2' < filename
Question 7. Write A Command To Remove All The Occurrences Of The Word "jhon" Except The First One In A Line With In The Entire File?
Answer :
sed 's/jhon//2g' < filename
Proofreader Interview Questions
Question eight. Write A Command To Remove The First Number On Line 5 In File?
Answer :
sed 'five s/[0-9][0-9]*//' < filename
Question 9. Write A Command To Remove The First Number On All Lines That Start With "@"?
Answer :
sed ',^@, s/[0-9][0-9]*//' < filename
Communication Skills Interview Questions
Question 10. Write A Command To Replace The Word "gum" With "drum" In The First one hundred Lines Of A File?
Answer :
sed '1,00 s/gum/drum/' < filename
Question 11. Write A Command To Replace The Word "lite" With "mild" From one centesimal Line To Last Line In A File?
Answer :
sed 'a hundred,$ s/lite/mild/' < filename
Video Editing Interview Questions
Question 12. Write A Command To Remove The First 10 Lines From A File?
Answer :
sed '1,10 d' < filename
Adobe Photoshop Interview Questions
Question 13. Write A Command To Duplicate Each Line In A File?
Answer :
sed 'p' < filename
Question 14. Write A Command To Duplicate Empty Lines In A File?
Answer :
sed '/^$/ p' < filename
Question 15. Write A Sed Command To Print The Lines That Do Not Contain The Word "run"?
Answer :
sed -n '/run/!P' < filename
Medical Transcription Interview Questions
Question 16. What Is Sed?
Answer :
"sed" stands for Stream EDitor. Sed is a non-interactive editor, written by the late Lee E. McMahon in 1973 or 1974.
Instead of altering a file interactively by moving the cursor on the screen (as with a word processor), the user sends a script of editing instructions to sed, plus the name of the file to edit (or the text to be edited may come as output from a pipe). In this sense, sed works like a filter -- deleting, inserting and changing characters, words, and lines of text. Its range of activity goes from small, simple changes to very complex ones.
Sed reads its input from stdin (Unix shorthand for "standard input," i.E., the console) or from files (or both), and sends the results to stdout ("standard output," normally the console or screen). Most people use sed first for its substitution features. Sed is often used as a find-and-replace tool.
Sed 's/Glenn/Harold/g' oldfile >newfile
will update every occurrence of "Glenn" with the word "Harold", wherever it occurs inside the document. The "locate" element is a ordinary expression ("RE"), which may be a easy phrase or may additionally contain special characters to allow more flexibility (for example, to save you "Glenn" from also matching "Glennon").
My first actual use of sed was to feature eight areas to the left facet of a file, so once I revealed it, the printing would not begin on the absolute left fringe of a piece of paper.
     Sed 's/^/        /' myfile >newfile   # my first sed script
     sed 's/^/        /' myfile subsequent sed script
Then I discovered that sed could show most effective one paragraph of a document, beginning on the phrase "and in which it came" and ending at the word "for all people". My script seemed like this:
sed -n '/and in which it got here/,/for all people/p' myfile
Sed's normal conduct is to print (i.E., display or show on display screen) the complete record, which includes the components that haven't been altered, until you operate the -n transfer. The "-n" stands for "no output". This switch is sort of continually used together with a 'p' command someplace, which says to print most effective the sections of the document that have been targeted. The -n transfer with the 'p' command permit for elements of a record to be printed (i.E., sent to the console).
Next, I determined that sed should show me most effective (say) lines 12-18 of a document and not display me the relaxation. This turned into very on hand when I had to evaluate simplest part of an extended document and I did not need to alter it.
# the 'p' stands for print
sed -n 12,18p myfile
Likewise, sed may want to show me the whole thing else BUT the ones precise traces, with out physically changing the file at the disk:
     # the 'd' stands for delete
     sed 12,18d myfile
Sed could also double-space my unmarried-spaced record when it got here time to print it:
sed G myfile >newfile
If you've got many modifying commands (for deleting, adding, substituting, and so on.) which would possibly take in numerous strains, those instructions can be put into a separate document and all of the commands inside the file implemented to record being edited:
     #  'script.Sed' is the file of instructions
     # 'myfile' is the report being changed
     sed -f script.Sed myfile  # 'script.Sed' is the file of instructions
Question 17. What Versions Of Sed Are There, And Where Can I Get Them?
Answer :
Note: "Free" does now not mean "public domain" nor does it always imply you may in no way be charged for it. All versions of sed on this segment besides the CP/M variations are based totally at the GNU widespread public license and are "loose software" by using that widespread. This way you can get the supply code and increase it further.
At the URLs indexed in this class, sed binaries or supply code can be downloaded and used without expenses or license bills.
Vi Editor Interview Questions
Question 18. How Do I Insert A Newline Into The Rhs Of A Substitution?
Answer :
Several versions of sed allow 'n' to be typed at once into the RHS, that is then transformed to a newline on output: ssed, gsed302a+, gsed103 (with the -x transfer), sed15+, sedmod, and UnixDOS sed. The simplest answer is to apply this sort of variations.
For different versions of sed, strive one of the following:
(a) If typing the sed script from a Bourne shell, use one backslash "" if the script uses 'unmarried quotes' or two backslashes "" if the script requires "double rates". In the example underneath, word that the main '>' at the 2d line is generated with the aid of the shell to activate the consumer for greater enter. The person types in shrink, unmarried-quote, after which sed 's//& new
     >/'
     two new
     traces
     [bash-prompt]$
(b) Use a script file with one backslash '' within the script, right away observed via a newline. This will embed a newline into the "replace" component. Example:
     sed -f newline.Sed documents
 
     # newline.Sed
     s/twolines/two new
     strains/g
Some variations of sed may not want the trailing backslash. If so, take away it.
(c) Insert an unused character and pipe the output through sed 's//& new=/' two new
     lines
(d) Use the "G" command:
G appends a newline, plus the contents of the preserve space to the quit of the sample area. If the keep area is empty, a newline is appended besides. The newline is saved in the pattern area as "n" wherein it may be addressed with the aid of grouping "(...)" and moved within the RHS. Thus, to change the "twolines" instance used in advance, the following script will paintings:
sed '/twolines/G;s/()(traces)(n)/132/;'
(e) Inserting full lines, now not breaking strains up:
If one isn't always changing lines however best placing complete traces before or after a sample, the method is an awful lot less difficult. Use the "i" (insert) or "a" (append) command, making the alterations through an outside script. To insert "This line is new" BEFORE every line matching a regex:
     /RE/i This line is new   # HHsed, sedmod, gsed three.02a
     /RE/x;s/$/This line is new/;G;   # other seds
The examples above are intended as "one-line" commands entered from the console. If the use of a sed script, "i" straight away accompanied through a literal newline will paintings on all versions of sed. Furthermore, the command "s/$/This line is new/" will only paintings if the maintain area is already empty (which it is with the aid of default).
To append "This line is new" AFTER every line matching a regex:
/RE/a This line is new   # HHsed, sedmod, gsed 3.02a
/RE/G;s/$/This line is new/;  # other seds
To append 2 blank traces after each line matching a regex:
/RE/G;G; # assumes the maintain space is empty
To replace every line matching a regex with 5 clean strains:
/RE/s/.*//;G;G;G;G;# assumes the hold area is empty
(f) Use the "y///" command if possible:
On a few Unix variations of sed (no longer GNU sed!), although the s/// command might not accept 'n' in the RHS, the y/// command does. If your Unix sed helps it, a newline after "aaa" can be inserted this manner (which is not transportable to GNU sed or other seds):
s/aaa/&~/; y/~/n/; #assuming no other '~' is on the road!
Audio Editor Interview Questions
Question 19. How Do I Represent Control-codes Or Nonprintable Characters?
Answer :
Several versions of sed guide the notation xHH, where "HH" are hex digits, 00-FF: ssed, GNU sed v3.02.Eighty and above, GNU sed v1.03, sed16 and sed15 (HHsed). Try to apply one of these versions.
Sed isn't always intended to method binary or item code, and documents which incorporate nulls (0x00) will usually generate errors in maximum versions of sed. The cutting-edge versions of GNU sed and ssed are an exception; they allow nulls in the enter files and additionally in regexes.
On Unix platforms, the 'echo' command may permit insertion of octal or hex values, e.G., `echo "nnn"` or `echo -n "nnn"`. The echo command can also guide syntax like 'b' or 't' for backspace or tab characters. Check the person pages to peer what syntax your model of echo supports. Some variations help the following:
     # replace 0x1A (32 octal) with ASCII letters
     sed 's/'`echo "32"`'/Ctrl-Z/g'
     # be aware the 3 backslashes inside the command beneath
     sed "s/.`echo b`//g"
Question 20. How Do I Convert Files With Toggle Characters, Like +this+, To Look Like [i]this[/i]?
Answer :
Input documents, specifically message-oriented text files, frequently incorporate toggle characters for emphasis, like ~this~, this, or =this=. Sed could make the equal enter pattern produce alternating output whenever it is encountered. Typical wishes might be to generate HMTL codes or print codes for boldface, italic, or underscore. This script accomodates a couple of occurrences of the toggle sample at the identical line, as well as instances where the sample begins on one line and finishes numerous traces later, even on the give up of the report:
     # sed script to transform +this+ to [i]this[/i]
     :a
   /+/ x;  # If "+" is determined, switch preserve and pattern area
      /^ON/ # If "ON" is inside the (former) keep area, then ..
         S///;     # .. Delete it
         x;      # .. Transfer hold space and sample area returned
         sturn the subsequent "+" into "[/i]"
         ba;       # .. Jump back to label :a and begin over
       
     s/^/ON/;  # Else, "ON" become not in the maintain area; create it
     x;            # Switch preserve area and sample area;      # Turn the primary "+" into "[i]"
     ba;         # Branch to label :a to locate another pattern
     
     #---stop of script---
This script makes use of the preserve space to create a "flag" to suggest whether or not the toggle is ON or not. We have delivered comments to illustrate the script logic, but in maximum versions of sed remarks are not accredited after 'b'ranch instructions or labels.
If you are sure that the +toggle+ characters never go line boundaries (i.E., by no means begin on one line and cease on another), this script can be decreased to 1g
If your toggle sample consists of regex metacharacters (which includes '*' or perhaps '+' or '?'), take into account to quote them with backslashes.
Content Writer Interview Questions
Question 21. How Do I Perform A Case-insensitive Search?
Answer :
Several versions of sed support case-insensitive matching: ssed and GNU sed v3.02+ (with I flag after s/// or /regex/); sedmod with the -i switch; and sed16 (which helps both forms of switches).
With different variations of sed, case-insensitive looking is awkward, so human beings may also use awk or perl instead, considering that those applications have options for case-insensitive searches. In gawk/mawk, use "BEGIN IGNORECASE=1" and in perl, "/regex/i". For different seds, here are three solutions:
Solution 1: convert the whole thing to top case and search typically
     # sed script, solution 1
     h;          # replica the unique line to the maintain space
                 # convert the pattern area to strong caps
 y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
                 # now we are able to search for the word "CARLOS"
     /CARLOS/ 
          # upload or insert strains. Note: "s/.../.../" will now not paintings
          # here because we're looking a changed pattern
          # area and are not printing the sample space.
     
     X;          # get returned the original pattern area
                 # the original pattern space could be printed
     #---stop of sed script---
Solution 2: look for each cases
Often, right names will either begin with all decrease-case ("unix"), with an preliminary capital letter ("Unix") or arise in solid caps ("UNIX"). There can be no want to search for each possibility.
     /UNIX/b healthy
     /[Uu]nix/b suit
Solution 3: look for all feasible instances
     # If you ought to, look for any viable mixture
     /[Ca][Aa][Rr][Ll][Oo][Ss]/  ... 
Bear in mind that because the sample period increases, this answer turns into an order of value slower than the one of Solution 1, at least with some implementations of sed.
Question 22. How Do I Match Only The First Occurrence Of A Pattern?
Answer :
(1) The widespread answer is to use GNU sed or ssed, with this sort of range expressions. The first script ("print best the first fit") works with any version of sed:
  sed -n '/RE/p;q;' report       # print handiest the primary in shape
  sed 'zero,/RE///d;' record     # delete only the primary healthy
  sed '0,/RE/s//to_that/' file  # trade simplest the primary match
(2) If you can't use GNU sed and in case you understand the pattern will now not occur on the primary line, this may paintings:
  sed '1,/RE///d;' report     # delete only the first in shape
  sed '1,/RE/s//to_that/' file  # alternate best the primary in shape
(three) If you cannot use GNU sed and the sample would possibly arise on the primary line, use one of the following instructions (credit for quick GNU script goes to Donald Bruce Stewart):
sed '/RE/x;/Y/!S/^/Y/;h;d;;x;' report # delete (one manner)
sed -e '/RE/d;:a' -e '$!N;$ba' -e '' record  # delete (every other way)
sed '/RE/d;:a;N;$ba;' file # identical script, GNU sed
sed -e '/RE/s//to_that/;:a' -e '$!N;$!Ba' -e '' record # exchange
Still some other solution, the usage of a flag within the maintain space. This is transportable to all seds and works if the sample is on the first line:
# sed script to exchange "foo" to "bar" most effective on the first prevalence
     1x;s/^/first/;x;
     1,/foo/x;/first/s///;x;s/foo/bar/;
     #---quit of script---
Question 23. How Do I Handle Fixed-duration, Columnar Data?
Answer :
Sed handles fixed-length fields via (grouping) and backreferences (1, 2, 3 ...). If we've 3 fields of 10, 25, and nine characters in keeping with area, our sed script might appear like so:
 s/^(.10)(.25)(.Nine)/321/;  # Change the fields
        ^^^^^^^^^^^~~~~~~~~~~~==========           #   from 1,2,three to three,2,1
         field #1   subject #2   area #3
This is a bit tough to examine. By using GNU sed or ssed with the -r switch energetic, it can look like this:
s/^(.10)(.25)(.9)/321/; # Using the -r transfer
To delete a discipline in sed, use grouping and pass over the backreference from the field to be deleted. If the records is long or tough to work with, use ssed with the -R switch and the /x flag after an s/// command, to insert feedback and comments about the fields.
For statistics with many fields, use GNU awk with the FIELDWIDTHS variable set within the pinnacle of the script. For instance:
awk 'BEGINFIELDWIDTHS = "10 25 9"; print $3 $2 $1' record
This is tons less complicated to read than a similar sed script, particularly if there are extra than five or 6 fields to govern.
Blog Interview Questions
Question 24. How Do I Change Only One Section Of A File?
Answer :
You can in shape more than a few lines by using line range, via regexes (say, all lines among the phrases "from" and "till"), or by way of a combination of the 2. For more than one substitutions at the identical range, put the command(s) among braces ....
For instance:
     # update best between strains 1 and 20
     1,20 s/Johnson/White/g
     # replace everywhere EXCEPT among strains 1 and 20
     1,20 !S/Johnson/White/g
     # update handiest among phrases "from" and "until". Note the
     # use of as word boundary markers in GNU sed.
     /from/,/until/  s//magenta/g; s//cyan/g; 
     # update most effective from the words "ENDNOTES:" to the quit of report
     /ENDNOTES:/,$  s/Schaff/Herzog/g; s/Kraft/Ebbing/g; 
Proofreader Interview Questions
Question 25. How Do I Delete Or Change A Block Of Text If The Block Contains A Certain Regular Expression?
Answer :
The following deletes the block between 'start' and 'give up' inclusively, if and best if the block consists of the string 'regex'. Written by means of Russell Davies, with additional remarks:
     # sed script to delete a block if /regex/ suits inside it
     :t
     /begin/,/quit/     # For every line among these block markers..
        /quit/!         #   If we aren't at the /quit/ marker
           $!          #     nor the remaining line of the report,
              N;        #     add the Next line to the sample area
              bt
                       #   and branch (loop again) to the :t label.
                       # This line suits the /cease/ marker.
        /regex/d;       # If /regex/ suits, delete the block.
                       # Otherwise, the block might be printed.
     #---cease of script---
Note: When the script above reaches /regex/, the complete multi-line block is within the pattern area. To replace items in the block, use "s///". To alternate the entire block, use the 'c' (exchange) command:
     /regex/c
     1: This will update the complete block
     2: with these  lines of textual content.
Question 26. How Do I Locate A Paragraph Of Text If The Paragraph Contains A Certain Regular Expression?
Answer :
Assume that paragraphs are separated via clean traces. For regexes which are unmarried terms, use one of the following scripts:
     sed -e '/./H;$!D;' -e 'x;/regex/!D'      # most seds
     sed '/./H;$!D;;x;/regex/!D'              # GNU sed
To print paragraphs handiest if they include three particular ordinary expressions (RE1, RE2, and RE3), in any order within the paragraph:
sed -e '/./H;$!D;' -e 'x;/RE1/!D;/RE2/!D;/RE3/!D'
With this solution and the preceding one, if the paragraphs are excessively lengthy (more than 4k in duration), you could overflow sed's inner buffers.
Defect Reporting Interview Questions
Question 27. How Do I Match A Block Of Specific Consecutive Lines?
Answer :
There are three approaches to approach this problem:
Try to use a "/variety/, /expression/"
Try to use a "/multi-linenexpression/"
Try to apply a block of "literal strings"
We describe every technique in the following sections.
Communication Skills Interview Questions
Question 28. How Do I Address All The Lines Between Re1 And Re2, Excluding The Lines Themselves?
Answer :
Normally, to cope with the lines among two regular expressions, RE1 and RE2, one would try this: '/RE1/,/RE2/instructions;'. Excluding the ones lines takes an extra step. To placed 2 arrows before each line among RE1 and RE2, besides for those traces:
sed '1,/RE1/! /RE2/,/RE1/!S/^/>>/; ' input.Fil
The preceding script, although brief, may be difficult to comply with. It also requires that /RE1/ can't arise on the primary line of the input document. The following script, though it is no longer a one-liner, is simpler to examine and it lets in /RE1/ to appear on the primary line:
     # sed script to update all traces between /RE1/ and /RE2/,
     # with out matching /RE1/ or /RE2/
     /RE1/,/RE2/
       /RE1/b
       /RE2/b
       s/^/>>/
     
     #---end of script---
Question 29. How Do I Join Two Lines If Line #1 Ends In A [certain String]?
Answer :
sed -e :a -e '/$/N; s/n//; ta' file # all seds
sed ':a; /$/N; s/n//; ta' report  # GNU sed, ssed, HHsed
Note that this replaces the backslash-newline with not anything. You can also want to update the backslash-newline with a single area rather.
Resume Writer Interview Questions
Question 30. How Do I Join Two Lines If Line #2 Begins In A [certain String]?
Answer :
Suppose a line begins with a particular string. How do you bring that line as much as observe the preceding line In this situation, we want to fit the string "<<=" at the start of one line, carry that line up to the quit of the road earlier than it, and update the string with a single space:
sed -e :a -e '$!N;s/n<<=/ /;ta' -e 'P;D' report  # all seds
sed ':a; $!N;s/n<<=/ /;ta;P;D' file  # GNU, ssed, sed15+
Question 31. How Do I Change All Paragraphs To Long Lines?
Answer :
A frequent request is how to convert DOS-style textfiles, in which each line ends with "paragraph marker", to Microsoft-style textfiles, in which the "paragraph" marker only appears at the end of real paragraphs. Sometimes this question is framed as, "How do I remove the hard returns at the end of each line in a paragraph?"
The problem occurs because newer word processors don't work the same way older text editors did. Older text editors used a newline (CR/LF in DOS; LF alone in Unix) to end each line on screen or on disk, and used two newlines to separate paragraphs. Certain word processors wanted to make paragraph reformatting and reflowing work easily, so they use one newline to end a paragraph and never allow newlines within a paragraph. This means that textfiles created with standard editors (Emacs, vi, Vedit, Boxer, etc.) appear to have "hard returns" at inappropriate places. The following sed script finds blocks of consecutive nonblank lines (i.E., paragraphs of text), and converts each block into one long line with one "hard return" at the end.
     # sed script to change all paragraphs to long lines
     /./H; $!D;  # Put each paragraph into hold space
     x;   # Swap hold space and pattern space
 s/^(n)(..*)$/21/; # Move leading n to end of PatSpace
 s/n(.)/ 1/g;     # Replace all other n with 1 space
# Uncomment the following line to remove excess blank lines:
     # /./!D;
     #---end of sed script---
If the input files have formatting or indentation that conveys special meaning (like program source code), this script will remove it. But if the text still needs to be extended, try 'par' (paragraph reformatter) or the 'fmt' utility with the -t or -c switches and the width option (-w) set to a number like 9999.
Question 32. How Do I Export Or Pass Variables Back Into The Environment?
Answer :
Suppose that line #1, word #2 of the file 'terminals' contains a value to be put in your TERM environment variable. Sed cannot export variables directly to the shell, but it can pass strings to shell commands. To set a variable in the Bourne
shell:TERM=`sed 's/^[^ ][^ ]* ([^ ][^ ]*).*/1/;q' terminals`;
export TERM
If the second word were "Wyse50", this would send the shell command "TERM=Wyse50".
Question 33. How Do I Replace "/some/unix/path" In A Substitution?
Answer :
Technically, the normal meaning of the slash can be disabled by prefixing it with a backslash. Thus,
sed 's//some/UNIX/path//a/new/path/g' files
But this is hard to read and write. There is a better solution. The s/// substitution command allows '/' to be replaced by any other character (including spaces or alphanumerics). Thus,
sed 'suses 'single fees' in preference to "double costs." Unix shells never enlarge $variables in single charges.
Question 35. Where Are The Man Pages For Gnu Sed?
Answer :
Prior to GNU sed v3.02, there weren't any. Until these days, man pages disbursed with gsed were borrowed from old sources or from other compilations. None of them had been "reliable." GNU sed v3.02 had the primary actual set of authentic guy pages, and the documentation has substantially improved with GNU sed version four.Zero, which now consists of both man pages and textinfo pages.
Question 36. How Do I Tell What Version Of Sed I Am Using?
Answer :
Try entering "sed" all by itself at the command line, followed by means of no arguments or parameters. Also, attempt "sed --model". In a pinch, you may also try this:
strings sed model of 'strings' need to be a version of the Unix application of this call. It need to no longer be the DOS utility STRINGS.COM by using Douglas Boling.
Medical Transcription Interview Questions
Question 37. Does Sed Issue An Exit Code?
Answer :
Most versions of sed do not, but test the documentation that came with whichever version you are the use of. GNU sed troubles an exit code of 0 if the program terminated commonly, 1 if there have been errors inside the script, and 2 if there were mistakes for the duration of script execution.
 
   
    
 
  
  
  
  
  
 